import Editable from './Editable';

type EditableTextProps = {
  text: string;
  onSave: (text: string) => Promise<void> | void;
  showRender: (text: string) => React.ReactNode;
};

export default function EditableText({ text, onSave, showRender }: EditableTextProps) {
  return (
    <Editable initValue={text} onSave={onSave}>
      {({ status, onEdit, onCancel, onAsyncSave, value, setValue }) => {
        switch (status) {
          case 'editing': {
            return (
              <span>
                <input value={value} onChange={(e) => setValue(e.target.value)} />
                <button onClick={onCancel}>取消</button>
                <button onClick={() => onAsyncSave(value)}>保存</button>
              </span>
            );
          }
          case 'saving': {
            return <span>保存中...</span>;
          }
          case 'showing': {
            return (
              <span>
                {showRender(text)} <button onClick={onEdit}>修改</button>
              </span>
            );
          }
          default:
            return <span>BUG: Unknown Status: {status}</span>;
        }
      }}
    </Editable>
  );
}
